import request from '@/utils/request'
import { defineStore } from 'pinia'

export const useCityStore = defineStore(
  'city',
  () => {
    // 当前选择的城市
    const curCity = ref({
      cityId: 110100,
      name: '北京',
      pinyin: 'beijing',
      isHot: 1
    })

    const curCityId = computed(() => curCity.value.cityId)
    const curCityName = computed(() => curCity.value.name)

    // 修改当前选择的城市
    function setCurCity(payload: ICity) {
      curCity.value = payload
    }

    const cities = ref<ICity[]>([])

    const cityGroups = computed(() => {
      const result: { groupName: string; groupList: ICity[] }[] = []

      cities.value.forEach((city) => {
        const groupName = city.pinyin.charAt(0).toUpperCase()

        const index = result.findIndex((group) => group.groupName === groupName)

        if (index !== -1) {
          // 找到
          result[index].groupList.push(city)
        } else {
          // 没找到
          result.push({
            groupName,
            groupList: [city]
          })
        }
      })

      return result.sort((a, b) => a.groupName.charCodeAt(0) - b.groupName.charCodeAt(0))
    })

    const indexList = computed(() => {
      return cityGroups.value.map((item) => item.groupName)
    })

    const getCities = () => {
      request
        .get<{
          cities: ICity[]
        }>('mall.film-ticket.city.list')
        .then((result) => {
          cities.value = result.cities
        })
    }

    return {
      curCity,
      curCityId,
      curCityName,
      cityGroups,
      indexList,
      getCities,
      setCurCity
    }
  },
  {
    persist: true
  }
)
